package song.NO_20;

import java.util.ArrayList;
import java.util.Arrays;

public class IsValid {
    /**
     * 标志向量
     */
    private final ArrayList<String> fuhao = new ArrayList<>(){
        {
            add(")");
            add("]");
            add("}");
        }
    };
    private boolean is_valid = true;
    private String str;
    private static boolean func(final String left_fuhao, final String right_fuhao){
        /**
         * 判断函数，判断相邻左右括号是否匹配
         */
        StringBuilder strb = new StringBuilder();
        strb.append(left_fuhao).append(right_fuhao);
        var str = strb.toString();
        switch(str){
            case "()": return true;
            case "[]": return true;
            case "{}": return true;
            default: return false;
        }
    }
    public IsValid(){
        this.str = "";
    }
    public IsValid(final String str){
        this.str = str;
    }
    public void judge(){
        ArrayList<String> str_array = new ArrayList<String>(Arrays.asList(this.str.split("")));
        ArrayList<String> stack = new ArrayList<>();
        for (int i = str_array.size() - 1; i >= 0;){
            if (this.fuhao.indexOf(str_array.get(i)) != -1) {
                stack.add(0, str_array.get(i));
                str_array.remove(i);
            }
            else{
                var para1 = str_array.get(str_array.size()-1);
                String para2 = "";
                if (!stack.isEmpty()) para2 = stack.get(0);
                else {
                    this.is_valid = false;
                    break;
                }
                if (!IsValid.func(para1, para2)) {
                    this.is_valid = false;
                    break;
                }
                else {
                    stack.remove(0);
                    str_array.remove(i);
                }
            }
            --i;
        }
        //判断栈是否为空，栈为空一个原因是因为遇到括号不匹配的情况，另外一种情况是因为存储右括号的栈中存在多余的括号
        if (!stack.isEmpty()) this.is_valid = false;
    }
    public void print(){
        System.out.println(this.is_valid);
    }
    public static void main(String[] args){
        String s1 = "[[][[]]]";
        IsValid isvalid = new IsValid(s1);
        isvalid.judge();
        isvalid.print();
    }
}
